package com.atguigu.stuty.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author early morning
 * @Create 2025/4/24 19:42
 * @Description: 100个线程，每个线程加100次，求最后的number值
 */
public class CASDemo {
    private int number;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
       ++ number;
    }
    // ---------------------------------
    AtomicInteger atomicInteger =new AtomicInteger();

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        // atomicInteger.getAndIncrement();
        atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException {
        CASDemo casDemo = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                // Runnable 接口的实现类
                for (int i1 = 1; i1 <= 100; i1++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+ "\t" + "获取最后的结果为：" + casDemo.getNumber());
        System.out.println(Thread.currentThread().getName()+ "\t" + "获取最后的结果为：" + casDemo.getAtomicInteger());
    }
}
